import Comments from '@/model/Comments'
import Hands from '@/model/CommentsHands'
import { checkCode } from '@/common/Utils'
import { getJWTPayload } from '../common/Utils'
import moment from 'moment'
import qs from 'qs'
import List from '@/model/List'
import User from '@/model/User'
import CommentsHands from '@/model/CommentsHands'

//判断是否禁言
const canReply = async (ctx) => {
  let result = false
  const obj = await getJWTPayload(ctx.header.authorization)
  if (typeof obj._id === 'undefined') {
    return result
  } else {
    const user = await User.findByID(obj._id)
    if (user.status === '0') {
      result = true
    }
    return result
  }
}
class CommentsController {
  async getComments(ctx) {
    const params = qs.parse(ctx.request.query)
    const tid = params.tid
    const page = params.page ? params.page : 0
    const limit = params.limit ? params.limit : 10
    ///////////返回点赞状态
    let result = await Comments.getCommentsList(tid, page, limit)
    //判断是否登录 登录判断点赞信息
    let obj = {}
    if (typeof ctx.header.authorization !== 'undefined') {
      const obj = await getJWTPayload(ctx.header.authorization)
    }
    if (typeof obj._id !== 'undefined') {
      result = result.map((item) => item.toJSON())
      for (let i = 0; i < result.length; i++) {
        let item = result[i]
        item.handed = '0'
        const commentsHands = await CommentsHands.findOne({
          cid: item._id,
          uid: obj._id,
        })
        if (commentsHands && commentsHands.cid) {
          if (commentsHands.uid === obj._id) {
            item.handed = '1'
          }
        }
      }
    }
    /////////

    const total = await Comments.queryCount(tid)
    ctx.body = {
      code: 200,
      total,
      data: result,
      msg: '查询成功',
    }
  }
  //添加评论
  async addComents(ctx) {
    const check = await canReply(ctx)
    if (!check) {
      ctx.body = {
        code: 501,
        msg: '用户被禁言',
      }
      return
    }
    const { body } = ctx.request
    let code = body.code
    let sid = body.sid
    let content = body.content
    let tid = body.tid
    let result = await checkCode(sid, code)
    if (!result) {
      ctx.body = {
        code: 500,
        msg: '图片验证码不正确，请检查',
      }
      return
    }
    const obj = await getJWTPayload(ctx.header.authorization)
    const list = await List.findOne({ _id: tid })
    let Comment = new Comments({
      uid: list.uid,
      content: content,
      cuid: obj._id,
      tid: tid,
      created: moment().format('YYYY-MM-DD HH:mm:ss'),
    })
    let comments = await Comment.save()
    const num = await Comments.getTotal(list.uid)
    global.ws.send(
      list.uid,
      JSON.stringify({
        event: 'message',
        message: num,
      })
    )
    let result1 = await List.updateOne(
      { _id: tid },
      {
        $inc: {
          answer: 1,
        },
      }
    )
    if (result1.matchedCount === 1) {
      ctx.body = {
        code: 200,
        msg: '评论成功',
        data: comments,
      }
    } else {
      ctx.body = {
        code: 500,
        msg: '评论失败',
      }
    }
  }
  //修改评论
  async updataComment(ctx) {
    const check = await canReply(ctx)
    if (!check) {
      ctx.body = {
        code: 501,
        msg: '用户被禁言',
      }
      return
    }
    const { body } = ctx.request
    let code = body.code
    let sid = body.sid
    let cid = body.cid
    let result = await checkCode(sid, code)
    if (!result) {
      ctx.body = {
        code: 500,
        msg: '图片验证码不正确，请检查',
      }
      return
    }
    const obj = await getJWTPayload(ctx.header.authorization)
    const data = await Comments.updateOne({ _id: cid }, { $set: body })
    ctx.body = {
      code: 200,
      data: data,
    }
  }
  async setBest(ctx) {
    //对用户进行判断是不是作者
    const obj = await getJWTPayload(ctx.header.authorization)
    if (typeof obj === 'undefined' && obj._id !== '') {
      ctx.body = {
        code: 401,
        msg: '用户未登录,或者没授权',
      }
      return
    }
    const params = qs.parse(ctx.request.query)
    // console.log(params)
    const list = await List.findByUid(params.tid._id)
    if (list.uid._id == obj._id && list.isEnd === '0') {
      //作者本人能设置
      const id = params.tid._id
      const result = await List.updateOne(
        { _id: id },
        {
          $set: {
            isEnd: '1',
          },
        }
      )
      const result1 = await Comments.updateOne(
        { _id: params._id },
        {
          $set: {
            isBest: '1',
          },
        }
      )
      if (result.matchedCount === 1 && result1.matchedCount === 1) {
        const comments = await Comments.findByTid(params._id, params.cuid._id)
        const cid = comments[0].cuid
        const result2 = await User.updateOne(
          { _id: cid },
          {
            $inc: {
              favs: list.fav,
            },
          }
        )
        if (result2.matchedCount === 1) {
          ctx.body = {
            code: 200,
            msg: '采纳成功',
            data: result2,
          }
        } else {
          ctx.body = {
            code: 500,
            msg: '设置用户失败',
          }
        }
      }
      //反馈积分
    } else {
      ctx.body = {
        code: 500,
        msg: '帖子已经结贴无法重新设置',
      }
    }
  }
  //点赞
  async setHands(ctx) {
    const params = qs.parse(ctx.request.query)
    const cid = params.cid
    const cuid = params.cuid
    const obj = await getJWTPayload(ctx.header.authorization)
    //防止用户多次点
    let tmp = await CommentsHands.findByCid(cid, obj._id)
    if (tmp.length > 0) {
      ctx.body = {
        code: 500,
        msg: '你已经点过赞了,请手下留情',
      }
      return
    }
    const hands = new Hands({
      cid: cid,
      uid: obj._id,
      created: moment().format('YYYY-MM-DD HH:mm:ss'),
    })
    const data = await hands.save()
    const comments = await Comments.updateOne(
      { _id: cid, cuid: cuid },
      {
        $inc: {
          hands: 1,
        },
      }
    )
    if (comments.matchedCount === 1) {
      ctx.body = {
        code: 200,
        msg: '点赞成功',
        data: data,
      }
    } else {
      ctx.body = {
        code: 500,
        msg: '点赞失败',
      }
    }

    //更新comm里的hands
  }
}

export default new CommentsController()
